package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHUtil
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import org.json.JSONObject

/**
 * 工单消息通知API
 */

public class apiWoMessageEntrance implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWoMessageEntrance.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        // 初始化返回参数
        JSONObject result = new JSONObject();
        JSONObject resultJson = new JSONObject();
        //接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }
        log.info("[调用请求信息]:" + callJson);

        try {
            def obj_guid = request.getParameter("obj_guid"); //工单编号
            def task_guid = request.getParameter("task_guid"); //任务编号
            def op_type = request.getParameter("op_type"); //结案

            //非空校验
            String dealMessage = "";
            if (KHUtil.isNull(obj_guid) || KHUtil.isNull(task_guid) || KHUtil.isNull(op_type)) {
                dealMessage = KHUtil.isNullMSG("obj_guid", obj_guid) + KHUtil.isNullMSG("task_guid", task_guid) + KHUtil.isNullMSG("op_type", op_type);
                resultJson.put("resultcode", "0");//成功 1 失败 0
                resultJson.put("resultmessage", "接口调度失败!" + dealMessage);
                return resultJson.toString();
            }

            //获取工单信息(必须查询到)
            String queryMessageSQL = "select objective_guid,map_id,workorderid,customer_guid from objective where objective_guid='" + obj_guid + "'";
            log.info("执行任务数据查询SQL:" + queryMessageSQL);
            List WorkMessageList = eliteBean.chaxun_sql(queryMessageSQL, "dataSource");
            String objective_guid = "";
            String map_id = "";
            String workorderid = "";
            String customer_guid = "";
            if (WorkMessageList.size() > 0) {
                objective_guid = WorkMessageList.get(0).get("objective_guid");
                map_id = WorkMessageList.get(0).get("map_id");
                workorderid = WorkMessageList.get(0).get("workorderid");
                customer_guid = WorkMessageList.get(0).get("customer_guid");
            }

            //获取短信模板(必须查询到)
            String queryMessageContentSql = "select send_message from send_message_template where  SEND_TYPE='all' and map_id='" + map_id + "'";
            log.info("执行任务数据查询SQL:" + queryMessageSQL);
            List WorkMessageContentList = eliteBean.chaxun_sql(queryMessageContentSql, "dataSource");
            String message_content = "";
            String to_message_content = "";
            if (WorkMessageContentList.size() > 0) {
                message_content = WorkMessageContentList.get(0).get("send_message");
                if (!KHUtil.isNull(message_content)) {
                    log.debug("替换前内容内容：" + message_content);
                    to_message_content = message_content.replaceAll("\\{workorderno}", workorderid); //将模板中的工单编号替换
                    log.debug("替换通知内容结果：" + to_message_content);
                }

                //获取工单待通知人员信息(配置表数据+工单历史处理人数据)
                String querymessageUserSql = '''Select Distinct A1.Msg_Rolegroup, A1.Msg_Staff, A1.Map_Id, s.Loginname, s.Mobile
                                                  From (Select Send_To_Group As Msg_Rolegroup, Send_To_Staff As Msg_Staff, Map_Id
                                                          From Send_Message_Config s
                                                         Where Del_Flag = '1\'
                                                           And Map_Id = \'''' + map_id + '''\'
                                                        Union
                                                        Select Distinct Ws.Oldhandlegroup_Id As Msg_Rolegroup, Ws.Oldhandleby_Id As Msg_Staff, Ob.Map_Id As Map_Id
                                                          From Workorderstep3 Ws
                                                          Left Join Objective Ob
                                                            On Ws.Workorder_Guid = Ob.Objective_Guid
                                                         Where Ws.Workorder_Guid = \'''' + objective_guid + '''\') A1
                                                  Left Join Staff s
                                                    On A1.Msg_Staff = s.Staff_Id
                                                 Where s.Workstatus = 'ONLINE\'''';
                log.info("执行任务数据查询SQL:" + querymessageUserSql);
                List WorkMessageUserList = eliteBean.chaxun_sql(querymessageUserSql, "dataSource");
                log.info("执行工单查询数据SQL获取总条数:" + WorkMessageUserList.size());
                int sendSMS = 0;
                int sendAPP = 0;
                for (int i = 0; i < WorkMessageUserList.size(); i++) {
                    Map selectResultcm = WorkMessageUserList.get(i);
                    String msg_rolegroup = selectResultcm.get("msg_rolegroup");//组
                    String msg_staff = selectResultcm.get("msg_staff");//坐席编号
                    String msg_map_id = selectResultcm.get("map_id");//工单类型
                    String msg_loginname = selectResultcm.get("loginname");//登录账号
                    String msg_mobile = selectResultcm.get("mobile");//手机号码

                    if (!KHUtil.isNull(msg_mobile)) {
                        //短信通知
                        sendDataDB(eliteBean, "3", to_message_content, "", "", customer_guid, objective_guid, "sms", "", msg_mobile, "", task_guid, msg_rolegroup, msg_staff);
                        sendSMS++;
                    } else {
                        log.debug("发送失败-无满足规则的发送途径信息Mobile:" + msg_mobile);
                    }
                    //app通知
                    sendDataDB(eliteBean, "6", to_message_content, "", "", customer_guid, objective_guid, "app", "", msg_loginname, "", task_guid, msg_rolegroup, msg_staff);
                    sendAPP++;
                }
                resultJson.put("resultcode", "1");
                resultJson.put("resultmessage", "接口调度成功-发送数量:APP-" + sendAPP + " SMS-" + sendSMS);
            } else {
                resultJson.put("resultcode", "-1");
                resultJson.put("resultmessage", "接口调度成功-发送模板未获取!");
            }


        } catch (Exception e) {
            resultJson.put("resultcode", "0");
            resultJson.put("resultmessage", e.getMessage());
        }
        return resultJson.toString();
    }

    // 添加document表，发送数据DB处理
    public static void sendDataDB(EliteBean eliteBean, String Doctype, String Documentpath, String Documentpath2, String Comments, String Customer_Guid, String Objective_Guid, String Lockedby, String Stringfield1, String documentto, String Template_Id, String elitetask_guid, String msg_rolegroup, String msg_staff) {
        long startTime = System.currentTimeMillis();
        log.debug("开始将发送内容数据处理到DB:" + startTime);

        try {
            def InsertSQL = "Insert Into Documentout" +
                    "  (Documentout_Guid," +
                    "   Doctype," +
                    "   Status," +
                    "   Trialcount," +
                    "   Trialcountlimit," +
                    "   Documentpath," +
                    "   Comments," +
                    "   Documentto," +
                    "   Priority_Id," +
                    "   Customer_Guid," +
                    "   Objective_Guid," +
                    "   Createdby," +
                    "   Createddate," +
                    "   Lockedby," +
                    "   Stringfield1," +
                    "   Documentpath2," +
                    "   Openid," +
                    "   Template_Id," +
                    "   Expectedstartdate)" +
                    "Values" +
                    "  (Uuid()," +
                    "   '" + Doctype + "'," +
                    "   3," +
                    "   0," +
                    "   5," +
                    "   '" + Documentpath + "'," +
                    "   '" + Comments + "'," +
                    "   '" + documentto + "'," +
                    "   '1'," +
                    "   '" + Customer_Guid + "'," +
                    "   '" + Objective_Guid + "'," +
                    "   'SELITE'," +
                    "   Now()," +
                    "   '" + Lockedby + "'," +
                    "   '" + Stringfield1 + "'," +
                    "   '" + Documentpath2 + "'," +
                    "   '平湖海吉星'," +
                    "   '" + Template_Id + "'," +
                    "   Now())";
            eliteBean.update(InsertSQL, "dataSource");

            //记录通知信息表-只有等于6才记录防止记录重复
            if (Doctype == "6") {
                String InsertKnowSQL = "Insert Into Ph_Wo_Know_List (Rec_Guid, Objective_Guid, Elitetask_Guid, Send_Groupid, Send_Staffid, Send_Content, Createdtime) Values (Uuid(), '" + Objective_Guid + "', '" + elitetask_guid + "', '" + msg_rolegroup + "', '" + msg_staff + "', 'To:" + documentto + " Content:" + Documentpath + "', Now())";
                eliteBean.update(InsertKnowSQL, "dataSource");
            }

            log.debug("发送内容数据处理到DB时长(毫秒):" + (System.currentTimeMillis() - startTime));

        } catch (Exception e) {
            log.error("发送内容数据处理到DB时长(毫秒):" + (System.currentTimeMillis() - startTime) + " 处理失败(" + e.getMessage() + ")");
        }

    }
}

